﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace CustomAttributeLearn
{
    class Program
    {
        static void Main(string[] args)
        {

            Customer testCustomer = new Customer();
            try
            {
                testCustomer.CustomerCode = "donglite555555555555555555555555555555555555555555555555555";
                Console.WriteLine(testCustomer.CustomerCode.Length);
                Console.WriteLine(testCustomer.CustomerCode);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            System.Attribute[] attrs = System.Attribute.GetCustomAttributes(typeof(Customer));  // Reflection.
            foreach (System.Attribute attr in attrs)
            {
                if (attr is Check)
                {
                    Check a = (Check)attr;
                    System.Console.WriteLine("{0}", a.MaxLength);//说明方法也是可以的
                }
            }

            Console.ReadLine();
        }
    }




    [Serializable]
    class Check : Attribute
    {
        private int _MaxLength;
        public int MaxLength
        {
            get
            {
                if (_MaxLength > 500)
                {
                    return 0;
                }
                return _MaxLength;
            }
            set
            {
               
                if (value > _MaxLength)
                {
                    _MaxLength = value;
                    Console.WriteLine("不能超过MaxLength最大值设定");
                    throw new Exception("超过MaxLength最大值设定");
                }
                else
                {
                    _MaxLength = value;
                }

            }
        }


    }
    [Check(MaxLength = 8)]
    public class Customer
    {
        private string _CustomerCode;

        
        public string CustomerCode
        {
            get { return _CustomerCode; }

            set { _CustomerCode = value; }
        }
    }



}
